package com.android.clinic.app.ui.widget.dialog;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qiangxi.checkupdatelibrary.service.DownloadService;
import com.qiangxi.checkupdatelibrary.utils.NetWorkUtil;

/**
 * Created by cheng on 2018/4/25.
 */
public class UpdateDialog extends Dialog {

    private Context context;
    private View view;
    private TextView updateTitle;
    private TextView updateTime;
    private TextView updateVersion;
    private TextView updateSize;
    private TextView updateDesc;
    private LinearLayout updateDescLayout;
    private TextView updateNetworkState;
    private Button update;
    private Button noUpdate;
    private String mDownloadUrl;
    private String mTitle;
    private String mAppTime;
    private String mVersionName;
    private float mAppSize;
    private String mAppDesc;
    private String mAppName;
    private String mFilePath;
    private String mFileName;
    private int mIconResId;
    private boolean isShowProgress;
    private long timeRange;
    private Fragment mCompatFragmentCallback;
    private android.app.Fragment mFragmentCallback;
    public static final int UPDATE_DIALOG_PERMISSION_REQUEST_CODE = 0;

    public UpdateDialog(Context context) {
        super(context);
        this.isShowProgress = false;
        this.setDialogTheme();
        this.setCanceledOnTouchOutside(false);
        this.context = context;
    }

    public UpdateDialog(Context context, @NonNull Fragment fragment) {
        this(context);
        this.mCompatFragmentCallback = fragment;
    }

    public UpdateDialog(Context context, @NonNull android.app.Fragment fragment) {
        this(context);
        this.mFragmentCallback = fragment;
    }

    private void setDialogTheme() {
        this.requestWindowFeature(1);
        this.getWindow().addFlags(2);
        this.getWindow().setBackgroundDrawable(new ColorDrawable(0));
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.view = LayoutInflater.from(this.context).inflate(com.qiangxi.checkupdatelibrary.R.layout.checkupdatelibrary_update_dialog_layout, (ViewGroup)null);
        this.setContentView(this.view);
        this.initView();
        this.initData();
        this.initEvent();
    }

    private void initEvent() {
        this.update.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(UpdateDialog.this.context.getApplicationInfo().targetSdkVersion >= 23) {
                    if(Build.VERSION.SDK_INT >= 23) {
                        int permissionStatus = ContextCompat.checkSelfPermission(UpdateDialog.this.context, "android.permission-group.STORAGE");
                        if(permissionStatus != 0) {
                            if(UpdateDialog.this.mCompatFragmentCallback != null) {
                                UpdateDialog.this.mCompatFragmentCallback.requestPermissions(new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 0);
                            } else if(UpdateDialog.this.mFragmentCallback != null) {
                                UpdateDialog.this.mFragmentCallback.requestPermissions(new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 0);
                            } else {
                                ActivityCompat.requestPermissions((Activity) UpdateDialog.this.context, new String[]{"android.permission.WRITE_EXTERNAL_STORAGE"}, 0);
                            }
                        }
                    } else {
                        UpdateDialog.this.download();
                    }
                } else {
                    UpdateDialog.this.download();
                }
            }
        });
        this.noUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                UpdateDialog.this.dismiss();
            }
        });
    }

    public void download() {
        if(System.currentTimeMillis() - this.timeRange >= 1000L) {
            this.timeRange = System.currentTimeMillis();
            this.setNetWorkState();
            if(!NetWorkUtil.hasNetConnection(this.context)) {
                Toast.makeText(this.context, "当前无网络连接", 0).show();
            } else {
                Intent intent = new Intent(this.context, DownloadService.class);
                intent.putExtra("downloadUrl", this.mDownloadUrl);
                intent.putExtra("filePath", this.mFilePath);
                intent.putExtra("fileName", this.mFileName);
                intent.putExtra("iconResId", this.mIconResId);
                intent.putExtra("isShowProgress", this.isShowProgress);
                intent.putExtra("appName", this.mAppName);
                this.context.startService(intent);
                this.dismiss();
                Toast.makeText(this.context, "正在后台为您下载...", 0).show();
            }
        }
    }

    private void initData() {
        if(TextUtils.isEmpty(this.mTitle)) {
            this.updateTitle.setVisibility(8);
        } else {
            this.updateTitle.setText(this.mTitle);
        }

        if(TextUtils.isEmpty(this.mAppTime)) {
            this.updateTime.setVisibility(8);
        } else {
            this.updateTime.setText("发布时间:" + this.mAppTime);
        }

        if(TextUtils.isEmpty(this.mVersionName)) {
            this.updateVersion.setVisibility(8);
        } else {
            this.updateVersion.setText("版本:" + this.mVersionName);
        }

        if(this.mAppSize == 0.0F) {
            this.updateSize.setVisibility(8);
        } else {
            this.updateSize.setText("大小:" + this.mAppSize + "M");
        }

        if(TextUtils.isEmpty(this.mAppDesc)) {
            this.updateDescLayout.setVisibility(8);
        } else {
            this.updateDesc.setText(this.mAppDesc);
            this.updateDesc.setMovementMethod(ScrollingMovementMethod.getInstance());
        }

        this.setNetWorkState();
    }

    private void setNetWorkState() {
        if(NetWorkUtil.isWifiConnection(this.context)) {
            this.updateNetworkState.setText("当前为WiFi网络环境,可放心下载.");
            this.updateNetworkState.setTextColor(Color.parseColor("#629755"));
        } else if(NetWorkUtil.isMobileConnection(this.context)) {
            this.updateNetworkState.setText("当前为移动网络环境,下载将会消耗流量!");
            this.updateNetworkState.setTextColor(Color.parseColor("#BAA029"));
        } else if(!NetWorkUtil.hasNetConnection(this.context)) {
            this.updateNetworkState.setText("当前无网络连接,请打开网络后重试!");
            this.updateNetworkState.setTextColor(-65536);
        } else {
            this.updateNetworkState.setVisibility(8);
        }

    }

    private void initView() {
        this.updateTitle = (TextView)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.updateTitle);
        this.updateTime = (TextView)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.updateTime);
        this.updateVersion = (TextView)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.updateVersion);
        this.updateSize = (TextView)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.updateSize);
        this.updateDesc = (TextView)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.updateDesc);
        this.updateDescLayout = (LinearLayout)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.updateDescLayout);
        this.updateNetworkState = (TextView)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.updateNetworkState);
        this.update = (Button)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.update);
        this.noUpdate = (Button)this.view.findViewById(com.qiangxi.checkupdatelibrary.R.id.noUpdate);
    }

    public UpdateDialog setDownloadUrl(String downloadUrl) {
        this.mDownloadUrl = downloadUrl;
        return this;
    }

    public UpdateDialog setTitle(String title) {
        this.mTitle = title;
        return this;
    }

    public UpdateDialog setReleaseTime(String releaseTime) {
        this.mAppTime = releaseTime;
        return this;
    }

    public UpdateDialog setVersionName(String versionName) {
        this.mVersionName = versionName;
        return this;
    }

    public UpdateDialog setUpdateDesc(String updateDesc) {
        this.mAppDesc = updateDesc;
        return this;
    }

    public UpdateDialog setAppSize(float appSize) {
        this.mAppSize = appSize;
        return this;
    }

    public UpdateDialog setFilePath(String filePath) {
        this.mFilePath = filePath;
        return this;
    }

    public UpdateDialog setFileName(String fileName) {
        this.mFileName = fileName;
        return this;
    }

    public UpdateDialog setIconResId(int iconResId) {
        this.mIconResId = iconResId;
        return this;
    }

    public UpdateDialog setShowProgress(boolean isShowProgress) {
        this.isShowProgress = isShowProgress;
        return this;
    }

    public UpdateDialog setAppName(String appName) {
        this.mAppName = appName;
        return this;
    }

}
